package com.maple.soa.file;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * 文件上传
 * @author lijian
 * @date 2020/6/26
 */
@WebServlet(urlPatterns = "/upload")
@MultipartConfig(maxFileSize = 20 * 1024 * 1024)
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("file");
        long size = part.getSize();
        String contentType = part.getContentType();
        String fileName = part.getSubmittedFileName();

        System.out.println("文件：" + fileName + ",大小：" + size + ",类型：" + contentType);

        String header = part.getHeader("content-disposition");
        System.out.println("请求头：" + header);


        String suffix = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("文件后缀：" + suffix);

        String newFileName = UUID.randomUUID().toString() + suffix;
        System.out.println(newFileName);
        String filePath = req.getServletContext().getRealPath("WEB-INF/upload/");
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        System.out.println(filePath);
        part.write(filePath + newFileName);

        PrintWriter writer = resp.getWriter();
        writer.println("上传成功");
    }
}
